package com.setoption.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.setoption.entity.PageResult;
import com.setoption.enums.ExceptionEnums;
import com.setoption.exception.MyException;
import com.setoption.mapper.StudentManagerMapper;
import com.setoption.pojo.Students;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@Service
public class StudentManagerService {

    @Resource
    private StudentManagerMapper studentsMapper;

    public PageResult<Students> selectAllStu(Map<String, Object> map) {
        Integer pageNum = Integer.valueOf(map.get("page").toString());
        Integer pageSize = Integer.valueOf(map.get("limit").toString());
        PageHelper.startPage(pageNum, pageSize);
        Example example = new Example(Students.class);
        example.excludeProperties("studentPassword");
        List<Students> students = studentsMapper.selectByExample(example);
        PageInfo<Students> userPageInfo = new PageInfo<Students>(students);
        return new PageResult<Students>(userPageInfo.getTotal(), userPageInfo.getList());
    }

    public int addStudent(Map<String, Object> map) {
        Students students = new Students(String.valueOf(map.get("student_no")), String.valueOf(map.get("student_name")), String.valueOf(map.get("student_sex")), Integer.parseInt(map.get("student_age").toString()));
        return studentsMapper.insertSelective(students);
    }

    public int resetStuPassword(Map<String, Object> map) {
        Students students = new Students();
        students.setStudentPassword("000000");
        students.setId(Integer.valueOf(map.get("id").toString()));
        int result = studentsMapper.updateByPrimaryKeySelective(students);
        if (result == 0) {
            throw new MyException(ExceptionEnums.TABLE_SET_ERROR);
        }
        return result;
    }

    public int delStu(Map<String, Object> map) {
        int result = studentsMapper.deleteByIds(map.get("id").toString());
        if (result == 0) {
            throw new MyException(ExceptionEnums.TABLE_SET_ERROR);
        }
        return result;
    }
}
